<?php

declare(strict_types=1);

namespace app\yperp\command;

use app\cms\model\Support;
use app\yperp\common\Changhong;
use app\yperp\common\GdImage;
use app\yperp\common\yp\YpLogin;
use app\yperp\common\MyWebDriver;
use app\yperp\common\Tools;
use app\yperp\common\yp\YpExpress;
use app\yperp\common\yp\YpOrder;
use app\yperp\job\GoodsAsync;
use app\yperp\job\GoodsDetailAsync;
use app\yperp\job\MgtJob;
use app\yperp\job\SupplierAsync;
use app\yperp\logic\GoodsAsync as LogicGoodsAsync;
use app\yperp\logic\GoodsListAsync;
use app\yperp\logic\Standby;
use app\yperp\model\Supplier;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\ConsoleWriter;
use Exception;
// use Fastposter\Client;
use think\Queue;
use ZipArchive;
use Zxing\QrReader;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
use think\Db as ThinkDb;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
// 导入PHP内置的AES和MD5函数
use phpseclib3\Crypt\AES as AES;
use phpseclib3\Hash\MD5 as MD5;

class urltest extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];
    protected function configure()
    {
        // 指令配置
        $this->setName('urltest')
            ->setDescription('the urltest command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;

        Standby::getInstance()->sku_remove([1]);

 
    }

    // PHP中使用EBC模式和PKCS7填充进行加密
    function encryptEbcPkcs7($plaintext, $key)
    {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-ecb'));
        $encrypted = openssl_encrypt($plaintext, 'aes-256-ecb', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }

    // PHP中使用EBC模式和PKCS7填充进行解密
    function decryptEbcPkcs7($ciphertext, $key)
    {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-ecb'));
        $decrypted = openssl_decrypt(base64_decode($ciphertext), 'aes-256-ecb', $key, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }

    function getlistdb()
    {
        $goods_count = ThinkDb::name('yperp_supplier_goods_list')->where([])->count('id');
        for ($i = 1; $i <= $goods_count; $i++) {
            $goods =    ThinkDb::name('yperp_supplier_goods_list')->where(['id' => $i])->column('itemCoId,itemSpuId');
            yield $goods;
        }
    }


    function supplier()
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        try {
            $response = $client->request('GET', 'https://gyl.scm121.com/api/drp/mySupplier/queryMySupplier', [
                'query' => [
                    'sort' => 'cdp.APPLY_TIME desc, cdp.DAYS_ORDER_QTY desc, cdp.SHELVES_QTY desc',
                    'status' => '2',
                    'pageNum' => '1',
                    'pageSize' => '2000',
                    // 'extraData' => '{}'
                ],
                'headers' => [
                    'authorization' => module_config('yperp.jst_token'),
                ]
            ]);
            $data = $response->getBody()->getContents();

            $data = json_decode($data, true);

            if ($data['success'] == true) {
                foreach ($data['data'] as $value) {
                    $items['coId'] = $value['coId'];
                    $items['coName'] = $value['coName'];
                    $items['channelId'] = $value['channelId'];
                    $items['partnerId'] = $value['partnerId'];
                    $items['supplierId'] = $value['supplierId'];
                    $items['supplierName'] = $value['supplierName'];
                    $items['supplierLogo'] = $value['supplierLogo'];
                    $items['supplierTagNames'] = $value['supplierTagNames'];
                    $bool = ThinkDb::name('yperp_supplier_corp')->where(['partnerId' => $items['partnerId']])->value('partnerId');
                    if ($bool) {
                        ThinkDb::name('yperp_supplier_corp')->where(['partnerId' => $items['partnerId']])->update($items);
                    } else {
                        ThinkDb::name('yperp_supplier_corp')->where(['partnerId' => $items['partnerId']])->insert($items);
                    }
                }
            }
        } catch (GuzzleException $e) {
            return $e->getMessage();
        }
    }

    function goodslist($supplierId)
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        try {
            $response = $client->request('POST', 'https://gyl.scm121.com/api/goods/buyer/supplier/goods/list', [
                'json' => [
                    'sort' => 'spu.SALES_VOLUME DESC,spu.ID ASC',
                    'supplierId' => $supplierId,
                    'asyncFillField' => true,
                    'hasStock' => false,
                    'itemCodeVague' => '0',
                    'pageNum' => 1,
                    'pageSize' => 10000,
                    'styleCodeVague' => "0"

                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                    'authorization' => module_config('yperp.jst_token'),
                ]
            ]);
            $data = $response->getBody()->getContents();
            dump($supplierId);
            dump($data);
            $data = json_decode($data, true);

            if ($data['success'] == true) {
                foreach ($data['data'] as $value) {
                    $items['supplierId'] = $supplierId;
                    $items['spuId'] = $value['spuId'];
                    $items['itemCoId'] = $value['itemCoId'];
                    $items['itemName'] = $value['itemName'];
                    $items['itemSpuId'] = $value['itemSpuId'];
                    $items['saleSevenDesensitized'] = $value['saleSevenDesensitized'];
                    $items['saleThirtyDesensitized'] = $value['saleThirtyDesensitized'];
                    $items['styleCode'] = $value['styleCode'];
                    $items['supplierName'] = $value['supplierName'];
                    $items['shopName'] = $value['shopName'];
                    $items['brandId'] = $value['brandId'];
                    $items['brandName'] = $value['brandName'];
                    $items['categoryName'] = $value['categoryName'];
                    $items['created'] = $value['created'];
                    $items['updated'] = $value['updated'];

                    $bool = ThinkDb::name('yperp_supplier_goods_list')->where(['itemSpuId' => $items['itemSpuId']])->value('itemSpuId');
                    dump(['itemSpuId' => $items['itemSpuId'], 'itemCoId' => $items['itemCoId']]);
                    if ($bool) {
                        ThinkDb::name('yperp_supplier_goods_list')->where(['itemSpuId' => $items['itemSpuId']])->update($items);
                    } else {
                        ThinkDb::name('yperp_supplier_goods_list')->where(['itemSpuId' => $items['itemSpuId']])->insert($items);
                    }
                }
            }
        } catch (GuzzleException $e) {
            dump($e->getMessage());
            dump($e->getTraceAsString());
        }
    }

    function goodsdetail($itemCoId = '10412595', $itemSpuId = '89FC534859E4404EAB9C181167CB0F9E')
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        try {
            $response = $client->request('POST', 'https://gyl.scm121.com/api/goods/goods/queryGoodsDetail', [
                'json' => [
                    'itemCoId' => $itemCoId,
                    'itemSpuId' => $itemSpuId,
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                    'authorization' => module_config('yperp.jst_token'),
                    ]
            ]);
            $data = $response->getBody()->getContents();

            $data = json_decode($data, true);

            if ($data['success'] == true) {
                $value = $data['data'];

                $items['itemCoId'] = $itemCoId;
                $items['itemSpuId'] = $itemSpuId;

                $items['categoryId'] = $value['categoryId'];
                $items['categoryName'] = $value['categoryName'];
                $items['coId'] = $value['coId'];
                $items['created'] = $value['created'];
                $items['dealPriceNinetyMax'] = $value['dealPriceNinetyMax'];
                $items['itemCoId'] = $value['itemCoId'];
                $items['itemName'] = $value['itemName'];
                $items['itemDetailImages'] = json_encode($value['itemDetailImages']);
                $items['itemMainImage'] = json_encode($value['itemMainImage']);
                $items['itemSpuId'] = $value['itemSpuId'];
                $items['maxCostPrice'] = $value['maxCostPrice'];
                $items['maxSupplyPrice'] = $value['maxSupplyPrice'];
                $items['minCostPrice'] = $value['minCostPrice'];
                $items['minSalesPrice'] = $value['minSalesPrice'];
                $items['minSupplyPrice'] = $value['minSupplyPrice'];
                $items['saleFifteen'] = $value['saleFifteen'];
                $items['saleFifteenDesensitized'] = $value['saleFifteenDesensitized'];
                $items['saleSeven'] = $value['saleSeven'];
                $items['saleSevenDesensitized'] = $value['saleSevenDesensitized'];
                $items['saleThirty'] = $value['saleThirty'];
                $items['saleThree'] = $value['saleThree'];
                $items['saleThreeDesensitized'] = $value['saleThreeDesensitized'];
                $items['saleYesterday'] = $value['saleYesterday'];
                $items['saleYesterdayDesensitized'] = $value['saleYesterdayDesensitized'];
                $items['salesVolume'] = $value['salesVolume'];
                $items['salesVolumeDesensitized'] = $value['salesVolumeDesensitized'];
                $items['spuId'] = $value['spuId'];
                $items['supplierId'] = $value['supplierId'];
                $items['styleCode'] = $value['styleCode'];

                $this->goodsdetailsku($value['itemSkuList'], $itemCoId, $itemSpuId);
                $bool = ThinkDb::name('yperp_supplier_goods_detail')->where(['itemSpuId' => $items['itemSpuId']])->value('itemSpuId');
                if ($bool) {
                    ThinkDb::name('yperp_supplier_goods_detail')->where(['itemSpuId' => $items['itemSpuId']])->update($items);
                } else {
                    ThinkDb::name('yperp_supplier_goods_detail')->where(['itemSpuId' => $items['itemSpuId']])->insert($items);
                }
            }
        } catch (\Exception $e) {
            dump($e->getMessage());
            dump($e->getTraceAsString());
        }
    }

    function goodsdetailsku($datas, $itemCoId, $itemSpuId)
    {
        foreach ($datas as $value) {

            $items['id'] = $value['id'];
            $items['itemCoId'] = $itemCoId;
            $items['itemSpuId'] = $itemSpuId;
            $items['coId'] = $value['coId'];
            $items['spuId'] = $value['spuId'];

            $items['colour'] = $value['colour'];
            $items['costPrice'] = $value['costPrice'];
            $items['costPriceNew'] = $value['costPriceNew'];
            $items['dealPriceNinetyMax'] = $value['dealPriceNinetyMax'];
            $items['erpStyleCode'] = $value['erpStyleCode'];
            $items['itemCode'] = $value['itemCode'];
            $items['linePrice'] = $value['linePrice'];
            $items['pic'] = $value['pic'];
            $items['shortName'] = $value['shortName'];

            $items['stock'] = $value['stock'];
            $items['stockTime'] = $value['stockTime'];
            $items['supplyPrice'] = $value['supplyPrice'];


            $bool = ThinkDb::name('yperp_supplier_goods_detail_sku')->where(['id' => $items['id'], 'itemSpuId' => $items['itemSpuId']])->value('itemSpuId');
            if ($bool) {
                ThinkDb::name('yperp_supplier_goods_detail_sku')->where(['itemSpuId' => $items['itemSpuId']])->update($items);
            } else {
                ThinkDb::name('yperp_supplier_goods_detail_sku')->where(['itemSpuId' => $items['itemSpuId']])->insert($items);
            }
        }
    }


    function config()
    {
        $capabilities = DesiredCapabilities::chrome();
        $capabilities->setCapability(
            'goog:chromeOptions',
            [
                'prefs' => [
                    'download.default_directory' => '/home/seluser/Downloads',
                    'download.prompt_for_download' => false,
                    'download.directory_upgrade' => true,
                    'safebrowsing.enabled' => true,
                ],
            ]
        );
        return $capabilities;
    }
}
